package com.lin.service.MulThread;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.concurrent.*;

public class BlockingQueueCase {
    //初始任务队列
    static BlockingQueue<Task> blockingQueue;
    public static void produce(List<Task> taskList) throws InterruptedException {
        blockingQueue = new ArrayBlockingQueue<>(taskList.size());
        LinkedBlockingQueue<Task> queue = new LinkedBlockingQueue();
        //将任务放到任务队列中
        for (Task task : taskList) {
            blockingQueue.put(task);
        }
    }

    /**
     * 消费任务
     * @param consumerNum 消费者数量
     */
    public static void consume(int consumerNum, CountDownLatch latch){
        for(int i = 1; i <= consumerNum; i++){
            //消费者消费任务
            Thread thread = new Thread(() -> {
                Task task;
                //当任务队列中还有需要执行的任务
                while((task = blockingQueue.poll()) != null){
                    //业务执行
                    try {
                        Thread.sleep(task.getTime());
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + "完成任务:"+task.getName()+",耗时:"+task.getTime()+"毫秒");
                    latch.countDown();
                }
            },"线程"+i);
            thread.start();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        //模拟5个待执行任务
        List<Task> taskList = new ArrayList<>();
        taskList.add(new Task("CPU",2000L));
        taskList.add(new Task("主板",800L));
        taskList.add(new Task("内存",500L));
        taskList.add(new Task("显卡",1000L));
        taskList.add(new Task("电源",200L));
        //5个任务放到队列中
        produce(taskList);
        //latch用于主线程等待线程把任务都执行完毕
        CountDownLatch latch = new CountDownLatch(taskList.size());
        //2个消费者消费任务
        consume(2,latch);
        latch.await();
        System.out.println("任务都执行完毕");
    }
}
